﻿

using HalconDotNet;
using LeaderCCSLaserUI.Data;
using LeaderCCSLaserUI.Data.Extensions;
using LeaderCCSLaserUI.Models;
using LeaderCCSLaserUI.Services;
using Microsoft.EntityFrameworkCore;
using MotionRobot.Models;
using netDxf;

using netDxf.Entities;
using netDxf.Header;
using Newtonsoft.Json;
using NLog;
using Prism.Commands;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LeaderCCSLaserUI.ViewModels.Dialogs
{
    public class WorkPointDialogViewModel : DialogViewModel
    {
        #region 变量
        private Param? systemParam;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private readonly IGTSCardService gTSCard;
        private CancellationTokenSource source1;
        string lostfocusColor = "";
        private double mz1SafePos, mz2SafePos, mxYJogSpeed, mzJogSpeed;
        private double mleftWeldH, mrightWeldH, mleftWeldZ, mrightWeldZ, mleftBornH, mrightBornH;
        private int prePointListSelectedIndex = 0;
        #endregion
        #region 属性
        private XYPointDisp leftMark;
        public XYPointDisp LeftMark
        {
            get { return leftMark; }
            set { SetProperty(ref leftMark, value); }
        }
        private XYPointDisp leftDelta;
        public XYPointDisp LeftDelta
        {
            get { return leftDelta; }
            set { SetProperty(ref leftDelta, value); }
        }
        private XYPointDisp rightMark;
        public XYPointDisp RightMark
        {
            get { return rightMark; }
            set { SetProperty(ref rightMark, value); }
        }
        private XYPointDisp rightDelta;
        public XYPointDisp RightDelta
        {
            get { return rightDelta; }
            set { SetProperty(ref rightDelta, value); }
        }
        private XYPointDisp leftFirst;
        public XYPointDisp LeftFirst
        {
            get { return leftFirst; }
            set { SetProperty(ref leftFirst, value); }
        }
        private XYPointDisp rightFirst;
        public XYPointDisp RightFirst
        {
            get { return rightFirst; }
            set { SetProperty(ref rightFirst, value); }
        }
        private ObservableCollection<LwPolylineDisp> lwPolylineList;
        public ObservableCollection<LwPolylineDisp> LwPolylineList
        {
            get { return lwPolylineList; }
            set { SetProperty(ref lwPolylineList, value); }
        }
        private bool isBusy;
        public bool IsBusy
        {
            get { return isBusy; }
            set { SetProperty(ref isBusy, value); }
        }
        private int handIndex;
        public int HandIndex
        {
            get { return handIndex; }
            set { SetProperty(ref handIndex, value); }
        }
        private ObservableCollection<XYZPointDisp> pointList1;
        public ObservableCollection<XYZPointDisp> PointList1
        {
            get { return pointList1; }
            set { SetProperty(ref pointList1, value); }
        }
        private string leftWeldZ;
        public string LeftWeldZ
        {
            get { return leftWeldZ; }
            set { SetProperty(ref leftWeldZ, value); }
        }
        private string leftWeldH;
        public string LeftWeldH
        {
            get { return leftWeldH; }
            set { SetProperty(ref leftWeldH, value); }
        }
        private string rightWeldZ;
        public string RightWeldZ
        {
            get { return rightWeldZ; }
            set { SetProperty(ref rightWeldZ, value); }
        }
        private string rightWeldH;
        public string RightWeldH
        {
            get { return rightWeldH; }
            set { SetProperty(ref rightWeldH, value); }
        }
        private string leftBornH;
        public string LeftBornH
        {
            get { return leftBornH; }
            set { SetProperty(ref leftBornH, value); }
        }
        private string rightBornH;
        public string RightBornH
        {
            get { return rightBornH; }
            set { SetProperty(ref rightBornH, value); }
        }
        private int pointListSelectedIndex;
        public int PointListSelectedIndex
        {
            get { return pointListSelectedIndex; }
            set { SetProperty(ref pointListSelectedIndex, value); }
        }
        private double leftCameraGrabZPos;
        public double LeftCameraGrabZPos
        {
            get { return leftCameraGrabZPos; }
            set { SetProperty(ref leftCameraGrabZPos, value); }
        }
        private double rightCameraGrabZPos;
        public double RightCameraGrabZPos
        {
            get { return rightCameraGrabZPos; }
            set { SetProperty(ref rightCameraGrabZPos, value); }
        }
        private double drawWidth;
        public double DrawWidth
        {
            get { return drawWidth; }
            set { SetProperty(ref drawWidth, value); }
        }
        private double drawHeight;
        public double DrawHeight
        {
            get { return drawHeight; }
            set { SetProperty(ref drawHeight, value); }
        }
        #endregion
        #region 方法绑定
        private DelegateCommand openFileCommand;
        public DelegateCommand OpenFileCommand =>
            openFileCommand ?? (openFileCommand = new DelegateCommand(ExecuteOpenFileCommand));
        private DelegateCommand<object> teachPointCommand;
        public DelegateCommand<object> TeachPointCommand =>
            teachPointCommand ?? (teachPointCommand = new DelegateCommand<object>(ExecuteTeachPointCommand));
        private DelegateCommand<object> selectHandCommand;
        public DelegateCommand<object> SelectHandCommand =>
            selectHandCommand ?? (selectHandCommand = new DelegateCommand<object>(ExecuteSelectHandCommand));
        private DelegateCommand<object> pointList1RowEditEndingCommand;
        public DelegateCommand<object> PointList1RowEditEndingCommand =>
            pointList1RowEditEndingCommand ?? (pointList1RowEditEndingCommand = new DelegateCommand<object>(ExecutePointList1RowEditEndingCommand));
        private DelegateCommand<object> pointList1IsUseCheckCommand;
        public DelegateCommand<object> PointList1IsUseCheckCommand =>
            pointList1IsUseCheckCommand ?? (pointList1IsUseCheckCommand = new DelegateCommand<object>(ExecutePointList1IsUseCheckCommand));
        private DelegateCommand<object> pointList1TeachPosCommand;
        public DelegateCommand<object> PointList1TeachPosCommand =>
            pointList1TeachPosCommand ?? (pointList1TeachPosCommand = new DelegateCommand<object>(ExecutePointList1TeachPosCommand));
        private DelegateCommand<object> pointList1JumpPosCommand;
        public DelegateCommand<object> PointList1JumpPosCommand =>
            pointList1JumpPosCommand ?? (pointList1JumpPosCommand = new DelegateCommand<object>(ExecutePointList1JumpPosCommand));
        private DelegateCommand<object> pointList1GoPosCommand;
        public DelegateCommand<object> PointList1GoPosCommand =>
            pointList1GoPosCommand ?? (pointList1GoPosCommand = new DelegateCommand<object>(ExecutePointList1GoPosCommand));
        private DelegateCommand<object> pointList1SelectCommand;
        public DelegateCommand<object> PointList1SelectCommand =>
            pointList1SelectCommand ?? (pointList1SelectCommand = new DelegateCommand<object>(ExecutePointList1SelectCommand));
        private DelegateCommand<object> textBoxLostFocusCommand;
        public DelegateCommand<object> TextBoxLostFocusCommand =>
            textBoxLostFocusCommand ?? (textBoxLostFocusCommand = new DelegateCommand<object>(ExecuteTextBoxLostFocusCommand));
        private DelegateCommand<object> selectAllCommand;
        public DelegateCommand<object> SelectAllCommand =>
            selectAllCommand ?? (selectAllCommand = new DelegateCommand<object>(ExecuteSelectAllCommand));
        private DelegateCommand addCommand;
        public DelegateCommand AddCommand =>
            addCommand ?? (addCommand = new DelegateCommand(ExecuteAddCommand));
        private DelegateCommand<object> deletCommand;
        public DelegateCommand<object> DeletCommand =>
            deletCommand ?? (deletCommand = new DelegateCommand<object>(ExecuteDeletCommand));
        private DelegateCommand<object> shiftUpCommand;
        public DelegateCommand<object> ShiftUpCommand =>
            shiftUpCommand ?? (shiftUpCommand = new DelegateCommand<object>(ExecuteShiftUpCommand));
        private DelegateCommand<object> shiftDownCommand;
        public DelegateCommand<object> ShiftDownCommand =>
            shiftDownCommand ?? (shiftDownCommand = new DelegateCommand<object>(ExecuteShiftDownCommand));
        private DelegateCommand openFundationFileCommand;
        public DelegateCommand OpenFundationFileCommand =>
            openFundationFileCommand ?? (openFundationFileCommand = new DelegateCommand(ExecuteOpenFundationFileCommand));

       
        async void ExecuteOpenFundationFileCommand()
        {
            var result = _dialogHostService.Password("请输入密码");
            if (result == ButtonResult.Yes)
            {
                IsBusy = true;
                await Task.Delay(100);
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Dxf文件(*.dxf)|*.dxf|所有文件|*.*";
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    await Task.Run(() => {
                        // this check is optional but recommended before loading a DXF file
                        DxfVersion dxfVersion = DxfDocument.CheckDxfFileVersion(ofd.FileName, out var isBinary);
                        // netDxf is only compatible with AutoCad2000 and higher DXF version
                        if (dxfVersion < DxfVersion.AutoCad2000) return;
                        // load file
                        DxfDocument dxf = DxfDocument.Load(ofd.FileName);
                        LwPolyline? lwPolylinesBorder = dxf.LwPolylines.FirstOrDefault(p => p.Layer.Name == "外框");
                        if (lwPolylinesBorder != null)
                        {
                            var minx = lwPolylinesBorder.Vertexes.Min(p => p.Position.X);//载具图纸原点X
                            var miny = lwPolylinesBorder.Vertexes.Min(p => p.Position.Y);//载具图纸原点Y
                            var bwidth = lwPolylinesBorder.Vertexes.Max(p => p.Position.X) - minx;
                            var bheight = lwPolylinesBorder.Vertexes.Max(p => p.Position.Y) - miny;
                            systemParam.BorderWidth = Math.Round(bwidth, 3);
                            systemParam.BorderHeight = Math.Round(bheight, 3);
                            Insert? insertleftmark = dxf.Inserts.FirstOrDefault(insert => insert.Block.Name == "YD" && insert.Layer.Name == "LYD");
                            if (insertleftmark != null)
                            {
                                var cadx = insertleftmark.Position.X - minx;
                                var cady = insertleftmark.Position.Y - miny;
                                LeftDelta.X = systemParam.LeftDelta.X = Math.Round(cadx - systemParam.LeftMark.X, 3);
                                LeftDelta.Y = systemParam.LeftDelta.Y = Math.Round(cady - systemParam.LeftMark.Y, 3);
                            }
                            Insert? insertrightmark = dxf.Inserts.FirstOrDefault(insert => insert.Block.Name == "YD" && insert.Layer.Name == "RYD");
                            if (insertrightmark != null)
                            {
                                var cadx = insertrightmark.Position.X - minx;
                                var cady = insertrightmark.Position.Y - miny;
                                RightDelta.X = systemParam.RightDelta.X = Math.Round(cadx - systemParam.RightMark.X, 3);
                                RightDelta.Y = systemParam.RightDelta.Y = Math.Round(cady - systemParam.RightMark.Y, 3);
                            }
                            var jsonString = JsonConvert.SerializeObject(systemParam, Formatting.Indented);
                            File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"), jsonString);                            
                        }
                    });
                    MessageBox.Show("导入基准图纸完成。\n请重启软件，重新回原点！", "信息");
                }
                IsBusy = false;
            }
        }
        void ExecuteShiftDownCommand(object obj)
        {
            if (obj != null)
            {
                if (obj is XYZPointDisp xyzpoint)
                {
                    bool changed = false;
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    var p = mdb.XYZRPoints.FirstOrDefault(p => p.Id == xyzpoint.Id);
                    if (p != null)
                    {
                        var wp1 = mdb.XYZRPoints.Where(t => t.Hand == HandIndex && t.PcsOrder > xyzpoint.PcsOrder).OrderBy(t => t.PcsOrder).FirstOrDefault();
                        if (wp1 != null)
                        {
                            int box = wp1.PcsOrder;
                            int box1 = p.PcsOrder;
                            wp1.PcsOrder = box1;
                            p.PcsOrder = box;
                            mdb.SaveChanges();
                            changed = true;
                        }
                    }

                    if (changed)
                    {
                        PointList1.Clear();
                        var leftpoints = mdb.XYZRPoints.Where(p => p.Hand == HandIndex).OrderBy(p => p.PcsOrder);
                        if (leftpoints.Any())
                        {
                            leftpoints.ToList().ForEach(p => {
                                PointList1.Add(new XYZPointDisp
                                {
                                    Id = p.Id,
                                    Alias = p.Alias,
                                    Name = p.Name,
                                    X = p.X,
                                    Y = p.Y,
                                    Z = p.Z,
                                    H = p.H,
                                    X1 = p.X1,
                                    Y1 = p.Y1,
                                    LazerDocumentIndex = p.LazerDocumentIndex + 1,
                                    ProductIndex = p.ProductIndex + 1,
                                    PcsOrder = p.PcsOrder,
                                    IsUse = p.IsUse
                                });
                            });
                        }
                    }

                    if (prePointListSelectedIndex < PointList1.Count - 1)
                    {
                        PointListSelectedIndex = prePointListSelectedIndex + 1;
                    }
                    else
                    {
                        PointListSelectedIndex = prePointListSelectedIndex;
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteShiftUpCommand(object obj)
        {
            if (obj != null)
            {
                if (obj is XYZPointDisp xyzpoint)
                {
                    bool changed = false;
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    var p = mdb.XYZRPoints.FirstOrDefault(p => p.Id == xyzpoint.Id);
                    if (p != null)
                    {
                        var wp1 = mdb.XYZRPoints.Where(t => t.Hand == HandIndex && t.PcsOrder < xyzpoint.PcsOrder).OrderByDescending(t => t.PcsOrder).FirstOrDefault();
                        if (wp1 != null)
                        {
                            int box = wp1.PcsOrder;
                            int box1 = p.PcsOrder;
                            wp1.PcsOrder = box1;
                            p.PcsOrder = box;
                            mdb.SaveChanges();
                            changed = true;
                        }
                    }

                    if (changed)
                    {
                        PointList1.Clear();
                        var leftpoints = mdb.XYZRPoints.Where(p => p.Hand == HandIndex).OrderBy(p => p.PcsOrder);
                        if (leftpoints.Any())
                        {
                            leftpoints.ToList().ForEach(p => {
                                PointList1.Add(new XYZPointDisp
                                {
                                    Id = p.Id,
                                    Alias = p.Alias,
                                    X = p.X,
                                    Y = p.Y,
                                    Z = p.Z,
                                    H = p.H,
                                    X1 = p.X1,
                                    Y1 = p.Y1,
                                    LazerDocumentIndex = p.LazerDocumentIndex + 1,
                                    ProductIndex = p.ProductIndex + 1,
                                    PcsOrder = p.PcsOrder,
                                    IsUse = p.IsUse
                                });
                            });
                        }
                    }

                    if (prePointListSelectedIndex > 0)
                    {
                        PointListSelectedIndex = prePointListSelectedIndex - 1;
                    }
                    else
                    {
                        PointListSelectedIndex = prePointListSelectedIndex;
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteDeletCommand(object obj)
        {
            if (obj != null)
            {
                if (obj is XYZPointDisp xyzpoint)
                {
                    if (MessageBox.Show($"确认删除\"{xyzpoint.Alias}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                    {
                        try
                        {
                            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                            var p = mdb.XYZRPoints.FirstOrDefault(p => p.Id == xyzpoint.Id);
                            if (p != null)
                            {
                                mdb.XYZRPoints.Remove(p);
                                mdb.SaveChanges();
                            }
                            var lwp = LwPolylineList.FirstOrDefault(m => m.Id == xyzpoint.Id);
                            if (lwp != null)
                            {
                                LwPolylineList.Remove(lwp);
                            }
                            PointList1.Remove(xyzpoint);
                            MessageBox.Show("删除点位完成", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteAddCommand()
        {
            DialogParameters param = new DialogParameters();
            int count = PointList1.Count;
            string name = HandIndex == 0 ? "LP" : "RP";
            param.Add("Name", name + count.ToString());
            param.Add("HandIndex", HandIndex);
            param.Add("WeldZ", HandIndex == 0 ? mleftWeldZ : mrightWeldZ);
            dialogService.ShowDialog("AddPointDialog", param, arg => {
                if (arg.Result == ButtonResult.Yes)
                {
                    try
                    {
                        using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                        int pcsorder = 0;
                        if (mdb.XYZRPoints.Where(w => w.Hand == HandIndex).Any())
                        {
                            pcsorder = mdb.XYZRPoints.Where(w => w.Hand == 0).Max(t => t.PcsOrder);
                        }
                        var p1 = new XYZPoint
                        {
                            Name = arg.Parameters.GetValue<string>("Name"),
                            X = arg.Parameters.GetValue<double>("X"),
                            Y = arg.Parameters.GetValue<double>("Y"),
                            Z = arg.Parameters.GetValue<double>("Z"),
                            H = HandIndex == 0 ? mleftWeldH : mrightWeldH,
                            Alias = arg.Parameters.GetValue<string>("Alias"),                            
                            LazerDocumentIndex = 0,
                            ProductIndex = 0,
                            X1 = 0,
                            Y1 = 0,
                            Hand = HandIndex,
                            IsUse = true,
                            PcsOrder = pcsorder + 1
                        };
                        mdb.XYZRPoints.Add(p1);
                        mdb.SaveChanges();

                        var p = mdb.XYZRPoints.FirstOrDefault(p => p.PcsOrder == pcsorder + 1 && p.Hand == HandIndex);
                        if (p != null)
                        {
                            PointList1.Add(new XYZPointDisp
                            {
                                Id = p.Id,
                                Alias = p.Alias,
                                Name = p.Name,
                                X = p.X,
                                Y = p.Y,
                                Z = p.Z,
                                H = p.H,
                                X1 = p.X1,
                                Y1 = p.Y1,
                                LazerDocumentIndex = p.LazerDocumentIndex + 1,
                                ProductIndex = p.ProductIndex + 1,
                                PcsOrder = p.PcsOrder,
                                IsUse = p.IsUse
                            });

                            LwPolylineList.Add(new LwPolylineDisp
                            {
                                Id = p.Id,
                                Kind = 2,
                                Hand = p.Hand,
                                Left = 10 + (p.X - 10) / 2,
                                Bottom = 10 + (p.Y - 10) / 2,
                                Width = 10,
                                Height = 10,
                                BorderColor = p.Hand == 0 ? "#7B68EE" : "#FF007F",
                                BorderThickness = 1
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            });
        }
        void ExecuteSelectAllCommand(object obj)
        {
            try
            {
                using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                var leftpoints = mdb.XYZRPoints.Where(p => p.Hand == HandIndex).OrderBy(p => p.PcsOrder);
                if (leftpoints.Any())
                {
                    leftpoints.ToList().ForEach(p => {
                        p.IsUse = obj.ToString() == "0";
                    });
                    mdb.SaveChanges();
                }
                foreach (var item in PointList1)
                {
                    item.IsUse = obj.ToString() == "0";
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
        void ExecuteTextBoxLostFocusCommand(object obj)
        {
            try
            {
                using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                switch (obj.ToString())
                {
                    case "LeftWeldZ":
                        {
                            if (double.TryParse(LeftWeldZ, out var v))
                            {
                                mleftWeldZ = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "WeldZ" && m.Hand == 0);
                                if (_mParam != null)
                                {
                                    _mParam.Value = LeftWeldZ;
                                }
                            }
                        }
                        break;
                    case "LeftWeldH":
                        {
                            if (double.TryParse(LeftWeldH, out var v))
                            {
                                mleftWeldH = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "WeldH" && m.Hand == 0);
                                if (_mParam != null)
                                {
                                    _mParam.Value = LeftWeldH;
                                }
                            }
                        }
                        break;
                    case "LeftBornH":
                        {
                            if (double.TryParse(LeftBornH, out var v))
                            {
                                mleftBornH = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "BornH" && m.Hand == 0);
                                if (_mParam != null)
                                {
                                    _mParam.Value = LeftBornH;
                                }
                            }
                        }
                        break;          
                    case "RightWeldZ":
                        {
                            if (double.TryParse(RightWeldZ, out var v))
                            {
                                mrightWeldZ = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "WeldZ" && m.Hand == 1);
                                if (_mParam != null)
                                {
                                    _mParam.Value = RightWeldZ;
                                }
                            }
                        }
                        break;
                    case "RightWeldH":
                        {
                            if (double.TryParse(RightWeldH, out var v))
                            {
                                mrightWeldH = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "WeldH" && m.Hand == 1);
                                if (_mParam != null)
                                {
                                    _mParam.Value = RightWeldH;
                                }
                            }
                        }
                        break;
                    case "RightBornH":
                        {
                            if (double.TryParse(RightBornH, out var v))
                            {
                                mrightBornH = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "BornH" && m.Hand == 1);
                                if (_mParam != null)
                                {
                                    _mParam.Value = RightBornH;
                                }
                            }
                        }
                        break;
                    case "LeftFirst":
                        {
                            var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 0 && param.Name == "First");
                            if (_pointParam != null)
                            {
                                var _point = JsonConvert.DeserializeObject<MPoint>(_pointParam.Value);
                                _point.X = LeftFirst.X;
                                _point.Y = LeftFirst.Y;
                                _pointParam.Value = JsonConvert.SerializeObject(_point, Formatting.Indented);
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "RightFirst":
                        {
                            var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 1 && param.Name == "First");
                            if (_pointParam != null)
                            {
                                var _point = JsonConvert.DeserializeObject<MPoint>(_pointParam.Value);
                                _point.X = RightFirst.X;
                                _point.Y = RightFirst.Y;
                                _pointParam.Value = JsonConvert.SerializeObject(_point, Formatting.Indented);
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "LeftCameraGrabZPos":
                        {
                            var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 0 && param.Name == "CameraGrabZPos");
                            if (_pointParam != null)
                            {
                                _pointParam.Value = LeftCameraGrabZPos.ToString();
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "RightCameraGrabZPos":
                        {
                            var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 1 && param.Name == "CameraGrabZPos");
                            if (_pointParam != null)
                            {
                                _pointParam.Value = RightCameraGrabZPos.ToString();
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    default:
                        break;
                }
                mdb.SaveChanges();
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
     
        }
        void ExecutePointList1SelectCommand(object obj)
        {
            if (obj is XYZPointDisp xyzpoint)
            {
                prePointListSelectedIndex = PointListSelectedIndex;
                Debug.WriteLine(prePointListSelectedIndex);
                var _shaps = LwPolylineList.Where(l => l.BorderThickness == 3);
                if (_shaps.Any())
                {
                    _shaps.ToList().ForEach(l => {
                        l.BorderColor = lostfocusColor;
                        l.BorderThickness = 1;
                    });
                }
                var _shaps1 = LwPolylineList.FirstOrDefault(l => l.Id == xyzpoint.Id);
                if (_shaps1 != null)
                {
                    lostfocusColor = _shaps1.BorderColor;
                    _shaps1.BorderColor = "#00FF00";
                    _shaps1.BorderThickness= 3;
                }
            }
        }
        async void ExecutePointList1GoPosCommand(object obj)
        {
            if (obj is XYZPointDisp xyzpoint)
            {
                if (MessageBox.Show($"确认Go运动到\"{xyzpoint.Alias}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsBusy = true;
                    AxisParm axisX, axisY, axisZ;
                    switch (HandIndex)
                    {
                        case 0:
                            axisX = gTSCard.A1;
                            axisY = gTSCard.A2;
                            axisZ = gTSCard.A3;
                            break;
                        case 1:
                        default:
                            axisX = gTSCard.A5;
                            axisY = gTSCard.A6;
                            axisZ = gTSCard.A7;
                            break;
                    }
                    GTSCard.ServoOn(axisX);//X
                    GTSCard.ServoOn(axisY);//Y
                    GTSCard.ServoOn(axisZ);//Z
                    GTSCard.AxisPosSet(axisX, GTSCard.GetEnc(axisX));
                    GTSCard.AxisPosSet(axisY, GTSCard.GetEnc(axisY));
                    GTSCard.AxisPosSet(axisZ, GTSCard.GetEnc(axisZ));
                    source1 = new CancellationTokenSource();
                    CancellationToken token = source1.Token;
                    await Task.Run(() => GoAction(token, (xyzpoint.X + xyzpoint.X1), (xyzpoint.Y + xyzpoint.Y1), xyzpoint.Z, axisX, axisY, axisZ), token).ContinueWith(t => { IsBusy = false; });
                }
            }
        }
        async void ExecutePointList1JumpPosCommand(object obj)
        {
            if (obj is XYZPointDisp xyzpoint)
            {
                if (MessageBox.Show($"确认Jump运动到\"{xyzpoint.Alias}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsBusy = true;
                    AxisParm axisX, axisY, axisZ;
                    double zSafePos;
                    switch (HandIndex)
                    {
                        case 0:
                            axisX = gTSCard.A1;
                            axisY = gTSCard.A2;
                            axisZ = gTSCard.A3;
                            zSafePos = mz1SafePos;
                            break;
                        case 1:
                        default:
                            axisX = gTSCard.A5;
                            axisY = gTSCard.A6;
                            axisZ = gTSCard.A7;
                            zSafePos = mz2SafePos;
                            break;
                    }
                    GTSCard.ServoOn(axisX);//X
                    GTSCard.ServoOn(axisY);//Y
                    GTSCard.ServoOn(axisZ);//Z
                    GTSCard.AxisPosSet(axisX, GTSCard.GetEnc(axisX));
                    GTSCard.AxisPosSet(axisY, GTSCard.GetEnc(axisY));
                    GTSCard.AxisPosSet(axisZ, GTSCard.GetEnc(axisZ));
                    source1 = new CancellationTokenSource();
                    CancellationToken token = source1.Token;
                    await Task.Run(() => JumpAction(token, (xyzpoint.X + xyzpoint.X1), (xyzpoint.Y + xyzpoint.Y1), xyzpoint.Z, axisX, axisY, axisZ, zSafePos), token).ContinueWith(t => { IsBusy = false; });
                }
            }
        }
        void ExecutePointList1TeachPosCommand(object obj)
        {
            if (obj is XYZPointDisp xyzpoint)
            {
                if (MessageBox.Show($"确认示教\"{xyzpoint.Alias}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    switch (HandIndex)
                    {
                        case 0:
                            xyzpoint.X = Math.Round(GTSCard.GetEnc(gTSCard.A1), 3);
                            xyzpoint.Y = Math.Round(GTSCard.GetEnc(gTSCard.A2), 3);
                            xyzpoint.Z = Math.Round(GTSCard.GetEnc(gTSCard.A3), 3);
                            break; 
                        case 1:
                        default:
                            xyzpoint.X = Math.Round(GTSCard.GetEnc(gTSCard.A5), 3);
                            xyzpoint.Y = Math.Round(GTSCard.GetEnc(gTSCard.A6), 3);
                            xyzpoint.Z = Math.Round(GTSCard.GetEnc(gTSCard.A7), 3);
                            break;
                    }
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    var point = mdb.XYZRPoints.FirstOrDefault(p => p.Id == xyzpoint.Id);
                    if (point != null)
                    {
                        point.X = xyzpoint.X;
                        point.Y = xyzpoint.Y;
                        point.Z = xyzpoint.Z;
                        mdb.SaveChanges();
                    }
                }
            }
        }
        void ExecutePointList1IsUseCheckCommand(object obj)
        {
            if (obj is XYZPointDisp xyzpoint)
            {
                try
                {
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    var point = mdb.XYZRPoints.FirstOrDefault(p => p.Id == xyzpoint.Id);
                    if (point != null)
                    {
                        point.IsUse = xyzpoint.IsUse;
                        mdb.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }
            }
        }
        void ExecutePointList1RowEditEndingCommand(object obj)
        {
            if (obj is XYZPointDisp xyzpoint)
            {
                try
                {
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    var point = mdb.XYZRPoints.FirstOrDefault(p => p.Id == xyzpoint.Id);
                    if (point != null)
                    {
                        point.X = xyzpoint.X;
                        point.Y = xyzpoint.Y;
                        point.Z = xyzpoint.Z;
                        point.X1 = xyzpoint.X1;
                        point.Y1 = xyzpoint.Y1;
                        point.H = xyzpoint.H;
                        point.Name = xyzpoint.Name;
                        point.Alias = xyzpoint.Alias;
                        point.LazerDocumentIndex = xyzpoint.LazerDocumentIndex - 1;
                        point.ProductIndex = xyzpoint.ProductIndex - 1;
                        point.PcsOrder = xyzpoint.PcsOrder;
                        mdb.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }
            }
        }
        void ExecuteSelectHandCommand(object obj)
        {
            HandIndex = int.Parse(obj.ToString());
            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
            PointList1.Clear();
            var _shaps = LwPolylineList.Where(l => l.BorderThickness == 3);
            if (_shaps.Any())
            {
                _shaps.ToList().ForEach(l => {
                    l.BorderColor = lostfocusColor;
                    l.BorderThickness = 1;
                });
            }
            var leftpoints = mdb.XYZRPoints.Where(p => p.Hand == HandIndex).OrderBy(p => p.PcsOrder);
            if (leftpoints.Any())
            {
                leftpoints.ToList().ForEach(p => {
                    PointList1.Add(new XYZPointDisp
                    {
                        Id = p.Id,
                        Alias = p.Alias,
                        Name = p.Name,
                        X = p.X,
                        Y = p.Y,
                        Z = p.Z,
                        H = p.H,
                        X1 = p.X1,
                        Y1 = p.Y1,
                        LazerDocumentIndex = p.LazerDocumentIndex + 1,
                        ProductIndex = p.ProductIndex + 1,
                        PcsOrder = p.PcsOrder,
                        IsUse = p.IsUse
                    });
                });
            }
        }
        void ExecuteTeachPointCommand(object obj)
        {
            string dispName = string.Empty;
            switch (obj.ToString())
            {
                case "LeftMark":
                    dispName = "左Mark点";
                    break;
                case "RightMark":
                    dispName = "右Mark点";
                    break;
                case "LeftFirst":
                    dispName = "左首点";
                    break;
                case "RightFirst":
                    dispName = "右首点";
                    break;
                case "LeftCameraGrabZPos":
                    dispName = "左拍照高度";
                    break;
                case "RightCameraGrabZPos":
                    dispName = "右拍照高度";
                    break;
                default:
                    break;
            }
            if (MessageBox.Show($"确定示教{dispName}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                switch (obj.ToString())
                {
                    case "LeftMark":
                        LeftMark.X = systemParam.LeftMark.X = (GTSCard.GetEnc(gTSCard.A1) - systemParam.LeftDelta.X);
                        LeftMark.Y = systemParam.LeftMark.Y = (GTSCard.GetEnc(gTSCard.A2) - systemParam.LeftDelta.Y);
                        break;
                    case "RightMark":
                        RightMark.X = systemParam.RightMark.X = (GTSCard.GetEnc(gTSCard.A5) - systemParam.RightDelta.X);
                        RightMark.Y = systemParam.RightMark.Y = (GTSCard.GetEnc(gTSCard.A6) - systemParam.RightDelta.Y);
                        break;
                    case "LeftFirst":
                        {
                            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                            var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 0 && param.Name == "First");
                            if (_pointParam != null)
                            {
                                var _point = JsonConvert.DeserializeObject<MPoint>(_pointParam.Value);
                                LeftFirst.X = _point.X = Math.Round(GTSCard.GetEnc(gTSCard.A1), 3);
                                LeftFirst.Y = _point.Y = Math.Round(GTSCard.GetEnc(gTSCard.A2), 3);
                                _point.Z = Math.Round(GTSCard.GetEnc(gTSCard.A3), 3);
                                _pointParam.Value = JsonConvert.SerializeObject(_point, Formatting.Indented);
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "RightFirst":
                        {
                            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                            var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 1 && param.Name == "First");
                            if (_pointParam != null)
                            {
                                var _point = JsonConvert.DeserializeObject<MPoint>(_pointParam.Value);
                                RightFirst.X = _point.X = Math.Round(GTSCard.GetEnc(gTSCard.A5), 3);
                                RightFirst.Y = _point.Y = Math.Round(GTSCard.GetEnc(gTSCard.A6), 3);
                                _point.Z = Math.Round(GTSCard.GetEnc(gTSCard.A7), 3);
                                _pointParam.Value = JsonConvert.SerializeObject(_point, Formatting.Indented);
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "LeftCameraGrabZPos":
                        {
                            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                            var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 0 && param.Name == "CameraGrabZPos");
                            if (_pointParam != null)
                            {
                                LeftCameraGrabZPos = Math.Round(GTSCard.GetEnc(gTSCard.A3), 3);
                                _pointParam.Value = LeftCameraGrabZPos.ToString();
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "RightCameraGrabZPos":
                        {
                            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                            var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 1 && param.Name == "CameraGrabZPos");
                            if (_pointParam != null)
                            {
                                RightCameraGrabZPos = Math.Round(GTSCard.GetEnc(gTSCard.A7), 3);
                                _pointParam.Value = RightCameraGrabZPos.ToString();
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    default:
                        break;
                }
                var jsonString = JsonConvert.SerializeObject(systemParam, Formatting.Indented);
                File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"), jsonString);
            }
        }
        async void ExecuteOpenFileCommand()
        {
            IsBusy = true;
            await Task.Delay(100);
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Dxf文件(*.dxf)|*.dxf|所有文件|*.*";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                PointList1.Clear();
                await Task.Run(() => {
                    try
                    {
                        // this check is optional but recommended before loading a DXF file
                        DxfVersion dxfVersion = DxfDocument.CheckDxfFileVersion(ofd.FileName, out var isBinary);
                        // netDxf is only compatible with AutoCad2000 and higher DXF version
                        if (dxfVersion < DxfVersion.AutoCad2000) return;
                        // load file
                        DxfDocument dxf = DxfDocument.Load(ofd.FileName);
                        double lminx = 0, lminy = 0, rminx = 0, rminy = 0;
                        Insert? myleftfirst = dxf.Inserts.FirstOrDefault(p => p.Block.Name == "YD" && p.Layer.Name == "LYD");
                        if (myleftfirst != null)
                        {
                            lminx = myleftfirst.Position.X;
                            lminy = myleftfirst.Position.Y;
                        }
                        else
                        {
                            return;
                        }
                        Insert? myrightfirst = dxf.Inserts.FirstOrDefault(p => p.Block.Name == "YD" && p.Layer.Name == "RYD");
                        if (myrightfirst != null)
                        {
                            rminx = myrightfirst.Position.X;
                            rminy = myrightfirst.Position.Y;
                        }
                        else
                        {
                            return;
                        }
                        using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                        mdb.Database.ExecuteSqlRaw("DELETE FROM XYZRPoints");
                        mdb.Database.ExecuteSqlRaw("DELETE FROM FlyGrabPoints");
                        mdb.Database.ExecuteSqlRaw("DELETE FROM VisionPoints");
                        mdb.SaveChanges();
                        #region 点位
                        var leftpcses = dxf.Inserts.Where(p => p.Block.Name == "LDD" && p.Layer.Name == "LHD");
                        if (leftpcses.Any())
                        {
                            var pcsMinx = leftpcses.Min(p => p.Position.X);
                            var pcsMaxx = leftpcses.Max(p => p.Position.X);
                            var gap = pcsMaxx == pcsMinx ? 0.5 : (pcsMaxx - pcsMinx) / 9;
                            var halfgap = gap / 2;
                            int index = 0; int effictiveRowIndex = 0;
                            for (int i = 0; i < 10; i++)
                            {
                                var selectedpcs = leftpcses.Where(p => p.Position.X > pcsMinx - halfgap + i * gap && p.Position.X <= pcsMinx + halfgap + i * gap);
                                if (selectedpcs.Any())
                                {
                                    var selectedpcsList = selectedpcs.ToList();
                                    if (effictiveRowIndex % 2 == 0)
                                    {
                                        //升序
                                        selectedpcsList.Sort((x, y) => x.Position.Y.CompareTo(y.Position.Y));
                                    }
                                    else
                                    {
                                        //降序
                                        selectedpcsList.Sort((x, y) => y.Position.Y.CompareTo(x.Position.Y));
                                    }
                                    foreach (var item in selectedpcsList)
                                    {
                                        var cadx = item.Position.X - lminx + LeftFirst.X;
                                        var cady = item.Position.Y - lminy + LeftFirst.Y;
                                        var text = dxf.MTexts.FirstOrDefault(t => t.Layer.Name == "LHD" && Math.Sqrt(Math.Pow(t.Position.X - item.Position.X, 2) + Math.Pow(t.Position.Y - item.Position.Y, 2)) < 20);
                                        string name = "NA";
                                        if (text != null)
                                        {
                                            name = text.Value;
                                        }
                                        int pcsorder = index++;
                                        mdb.XYZRPoints.Add(new XYZPoint
                                        {
                                            Name = name,
                                            Alias = name,
                                            IsUse = true,
                                            PcsOrder = pcsorder,
                                            X = Math.Round(cadx, 3),
                                            Y = Math.Round(cady, 3),
                                            Z = mleftWeldZ,
                                            H = mleftWeldH,
                                            Hand = 0
                                        });
                                        mdb.VisionPoints.Add(new VisionPoint
                                        {
                                            Name = name,
                                            Hand = 0,
                                            PcsOrder = pcsorder,
                                            Rec1Row1 = 2048 / 2 - 100,
                                            Rec1Column1 = 2448 / 2 - 100,
                                            Rec1Row2 = 2048 / 2 + 100,
                                            Rec1Column2 = 2448 / 2 + 100,
                                            ModelKind = 0,
                                            ST_X = 100,
                                            ST_Y = 100,
                                            ST_Angle = 0,
                                            Target_X = 100,
                                            Target_Y = 100,
                                            Track = 0,
                                            ImagePcsOrder = 0,
                                            ImageKind = 0,
                                            CameraHand = 0,
                                            ScriptFileName = string.Empty
                                        });
                                    }
                                    effictiveRowIndex++;
                                }
                            }
                            mdb.SaveChanges();
                        }

                        var rightpcses = dxf.Inserts.Where(p => p.Block.Name == "RDD" && p.Layer.Name == "RHD");
                        if (rightpcses.Any())
                        {
                            var pcsMinx = rightpcses.Min(p => p.Position.X);
                            var pcsMaxx = rightpcses.Max(p => p.Position.X);
                            var gap = pcsMaxx == pcsMinx ? 0.5 : (pcsMaxx - pcsMinx) / 9;
                            var halfgap = gap / 2;
                            int index = 0; int effictiveRowIndex = 0;
                            for (int i = 0; i < 10; i++)
                            {
                                var selectedpcs = rightpcses.Where(p => p.Position.X > pcsMinx - halfgap + i * gap && p.Position.X <= pcsMinx + halfgap + i * gap);
                                if (selectedpcs.Any())
                                {
                                    var selectedpcsList = selectedpcs.ToList();
                                    if (effictiveRowIndex % 2 == 0)
                                    {
                                        //升序
                                        selectedpcsList.Sort((x, y) => x.Position.Y.CompareTo(y.Position.Y));
                                    }
                                    else
                                    {
                                        //降序
                                        selectedpcsList.Sort((x, y) => y.Position.Y.CompareTo(x.Position.Y));
                                    }
                                    foreach (var item in selectedpcsList)
                                    {
                                        var cadx = item.Position.X - rminx + RightFirst.X;
                                        var cady = item.Position.Y - rminy + RightFirst.Y;
                                        var text = dxf.MTexts.FirstOrDefault(t => t.Layer.Name == "RHD" && Math.Sqrt(Math.Pow(t.Position.X - item.Position.X, 2) + Math.Pow(t.Position.Y - item.Position.Y, 2)) < 20);
                                        string name = "NA";
                                        if (text != null)
                                        {
                                            name = text.Value;
                                        }
                                        int pcsorder = index++;
                                        mdb.XYZRPoints.Add(new XYZPoint
                                        {
                                            Name = name,
                                            Alias = name,
                                            IsUse = true,
                                            PcsOrder = pcsorder,
                                            X = Math.Round(cadx, 3),
                                            Y = Math.Round(cady, 3),
                                            Z = mrightWeldZ,
                                            H = mrightWeldH,
                                            Hand = 1
                                        });
                                        mdb.VisionPoints.Add(new VisionPoint
                                        {
                                            Name = name,
                                            Hand = 1,
                                            PcsOrder = pcsorder,
                                            Rec1Row1 = 2048 / 2 - 100,
                                            Rec1Column1 = 2448 / 2 - 100,
                                            Rec1Row2 = 2048 / 2 + 100,
                                            Rec1Column2 = 2448 / 2 + 100,
                                            ModelKind = 0,
                                            ST_X = 100,
                                            ST_Y = 100,
                                            ST_Angle = 0,
                                            Target_X = 100,
                                            Target_Y = 100,
                                            Track = 0,
                                            ImagePcsOrder = 0,
                                            ImageKind = 0,
                                            CameraHand = 1,
                                            ScriptFileName = string.Empty
                                        });
                                    }
                                    effictiveRowIndex++;
                                }
                            }
                            mdb.SaveChanges();
                        }
                        #endregion

                        #region 单拍
                        string calibfilepath1 = $"Camera\\Calib\\Left";
                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.Environment.CurrentDirectory, calibfilepath1, "CalibHomMat2D.tup"), out var CalibHomMat2D1);
                        HOperatorSet.AffineTransPoint2d(CalibHomMat2D1, 2048 / 2, 2448 / 2, out var qx, out var qy);
                        var leftdeltaX = systemParam.LeftCameraCalib.X - qx.D;
                        var leftdeltaY = systemParam.LeftCameraCalib.Y - qy.D;

                        var leftgrabs = dxf.Circles.Where(c => c.Layer.Name == "LDD");
                        if (leftgrabs.Any())
                        {
                            var pcsMinx = leftgrabs.Min(p => p.Center.X);
                            var pcsMaxx = leftgrabs.Max(p => p.Center.X);
                            var gap = pcsMaxx == pcsMinx ? 0.5 : (pcsMaxx - pcsMinx) / 5;
                            var halfgap = gap / 2;
                            int index = 0; int effictiveRowIndex = 0;
                            for (int i = 0; i < 6; i++)
                            {
                                var selectedpcs = leftgrabs.Where(p => p.Center.X > pcsMinx - halfgap + i * gap && p.Center.X <= pcsMinx + halfgap + i * gap);
                                if (selectedpcs.Any())
                                {
                                    var selectedpcsList = selectedpcs.ToList();
                                    if (effictiveRowIndex % 2 == 0)
                                    {
                                        //升序
                                        selectedpcsList.Sort((x, y) => x.Center.Y.CompareTo(y.Center.Y));
                                    }
                                    else
                                    {
                                        //降序
                                        selectedpcsList.Sort((x, y) => y.Center.Y.CompareTo(x.Center.Y));
                                    }
                                    foreach (var item in selectedpcsList)
                                    {
                                        var cadx = item.Center.X - lminx + LeftFirst.X;
                                        var cady = item.Center.Y - lminy + LeftFirst.Y;
                                        var hpoints = mdb.XYZRPoints.Where(p => p.Hand == 0).Select(p => new { PcsOrder = p.PcsOrder,Distance = Math.Sqrt(Math.Pow(p.X - cadx, 2) + Math.Pow(p.Y - cady, 2)) }); //组成新集合                                    
                                        if (hpoints.Any())
                                        {
                                            var _arr = hpoints.ToList().OrderBy(p => p.Distance).ToArray();
                                            var vpoint = mdb.VisionPoints.FirstOrDefault(point => point.Hand == 0 && point.PcsOrder == _arr[0].PcsOrder);
                                            if (vpoint != null)
                                            {
                                                int pcsorder = index++;
                                                vpoint.Track = 0;
                                                vpoint.ImagePcsOrder = pcsorder;
                                                vpoint.ImageKind = 0;
                                                mdb.FlyGrabPoints.Add(new FlyGrabPoint
                                                {
                                                    X = Math.Round(cadx + leftdeltaX, 3),
                                                    Y = Math.Round(cady + leftdeltaY, 3),
                                                    Z = LeftCameraGrabZPos,
                                                    PcsOrder = pcsorder,
                                                    Hand = 0,
                                                    Track = 0,
                                                    Kind = 0,
                                                    UseLight1 = true,
                                                    UseLight2 = true
                                                });
                                            }
                                        }
                                    }
                                    effictiveRowIndex++;
                                }
                            }
                            mdb.SaveChanges();
                        }

                        string calibfilepath2 = $"Camera\\Calib\\Right";
                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.Environment.CurrentDirectory, calibfilepath2, "CalibHomMat2D.tup"), out var CalibHomMat2D2);
                        HOperatorSet.AffineTransPoint2d(CalibHomMat2D2, 2048 / 2, 2448 / 2, out qx, out qy);
                        var rightdeltaX = systemParam.RightCameraCalib.X - qx.D;
                        var rightdeltaY = systemParam.RightCameraCalib.Y - qy.D;

                        var rightgrabs = dxf.Circles.Where(c => c.Layer.Name == "RDD");
                        if (rightgrabs.Any())
                        {
                            var pcsMinx = rightgrabs.Min(p => p.Center.X);
                            var pcsMaxx = rightgrabs.Max(p => p.Center.X);
                            var gap = pcsMaxx == pcsMinx ? 0.5 : (pcsMaxx - pcsMinx) / 5;
                            var halfgap = gap / 2;
                            int index = 0; int effictiveRowIndex = 0;
                            for (int i = 0; i < 6; i++)
                            {
                                var selectedpcs = rightgrabs.Where(p => p.Center.X > pcsMinx - halfgap + i * gap && p.Center.X <= pcsMinx + halfgap + i * gap);
                                if (selectedpcs.Any())
                                {
                                    var selectedpcsList = selectedpcs.ToList();
                                    if (effictiveRowIndex % 2 == 0)
                                    {
                                        //升序
                                        selectedpcsList.Sort((x, y) => x.Center.Y.CompareTo(y.Center.Y));
                                    }
                                    else
                                    {
                                        //降序
                                        selectedpcsList.Sort((x, y) => y.Center.Y.CompareTo(x.Center.Y));
                                    }
                                    foreach (var item in selectedpcsList)
                                    {
                                        var cadx = item.Center.X - rminx + RightFirst.X;
                                        var cady = item.Center.Y - rminy + RightFirst.Y;
                                        var hpoints = mdb.XYZRPoints.Where(p => p.Hand == 1).Select(p => new { PcsOrder = p.PcsOrder, Distance = Math.Sqrt(Math.Pow(p.X - cadx, 2) + Math.Pow(p.Y - cady, 2)) }); //组成新集合                                    
                                        if (hpoints.Any())
                                        {
                                            var _arr = hpoints.ToList().OrderBy(p => p.Distance).ToArray();
                                            var vpoint = mdb.VisionPoints.FirstOrDefault(point => point.Hand == 1 && point.PcsOrder == _arr[0].PcsOrder);
                                            if (vpoint != null)
                                            {
                                                int pcsorder = index++;
                                                vpoint.Track = 0;
                                                vpoint.ImagePcsOrder = pcsorder;
                                                vpoint.ImageKind = 0;
                                                mdb.FlyGrabPoints.Add(new FlyGrabPoint
                                                {
                                                    X = Math.Round(cadx + rightdeltaX, 3),
                                                    Y = Math.Round(cady + rightdeltaY, 3),
                                                    Z = RightCameraGrabZPos,
                                                    PcsOrder = pcsorder,
                                                    Hand = 1,
                                                    Track = 0,
                                                    Kind = 0,
                                                    UseLight1 = true,
                                                    UseLight2 = true
                                                });
                                            }
                                        }
                                    }
                                    effictiveRowIndex++;
                                }
                            }
                            mdb.SaveChanges();
                        }
                        #endregion

                        #region 飞拍
                        var leftpolylines = dxf.LwPolylines.Where(l => l.Layer.Name == "LFP");
                        if (leftpolylines.Any())
                        {
                            var polylinelist = leftpolylines.ToList();
                            // 升序
                            polylinelist.Sort((x, y) => x.Vertexes.Min(v => v.Position.Y).CompareTo(y.Vertexes.Min(v => v.Position.Y)));
                            for (int i = 0; i < polylinelist.Count; i++)
                            {
                                //插入路径
                                mdb.FlyGrabPoints.Add(new FlyGrabPoint
                                {
                                    PcsOrder = 0,
                                    Hand = 0,
                                    Track = i,
                                    Kind = 2,
                                    X = Math.Round(polylinelist[i].Vertexes[0].Position.X - lminx + LeftFirst.X + leftdeltaX, 3),
                                    Y = Math.Round(polylinelist[i].Vertexes[0].Position.Y - lminy + LeftFirst.Y + leftdeltaY, 3),
                                    Z = LeftCameraGrabZPos,
                                    UseLight1 = true,
                                    UseLight2 = true
                                });
                                int _endIndx = polylinelist[i].Vertexes.Count - 1;
                                mdb.FlyGrabPoints.Add(new FlyGrabPoint
                                {
                                    PcsOrder = 1,
                                    Hand = 0,
                                    Track = i,
                                    Kind = 2,
                                    X = Math.Round(polylinelist[i].Vertexes[_endIndx].Position.X - lminx + LeftFirst.X + leftdeltaX, 3),
                                    Y = Math.Round(polylinelist[i].Vertexes[_endIndx].Position.Y - lminy + LeftFirst.Y + leftdeltaY, 3),
                                    Z = LeftCameraGrabZPos,
                                    UseLight1 = true,
                                    UseLight2 = true
                                });

                                var _minY = polylinelist[i].Vertexes[0].Position.Y - 0.5;
                                var _maxY = polylinelist[i].Vertexes[0].Position.Y + 0.5;
                                int _pcsOrder = 0;
                                var circles = dxf.Circles.Where(circle => circle.Layer.Name == "LFP" && circle.Center.Y >= _minY && circle.Center.Y < _maxY);
                                if (circles != null)
                                {
                                    var circleList = circles.ToList();
                                    //升序
                                    circleList.Sort((x, y) => Math.Abs(x.Center.X - polylinelist[i].Vertexes[0].Position.X).CompareTo(Math.Abs(y.Center.X - polylinelist[i].Vertexes[0].Position.X)));

                                    foreach (var item in circleList)
                                    {
                                        var cadx = item.Center.X - lminx + LeftFirst.X;
                                        var cady = item.Center.Y - lminy + LeftFirst.Y;
                                        var hpoints = mdb.XYZRPoints.Where(p => p.Hand == 0).Select(p => new { PcsOrder = p.PcsOrder, Distance = Math.Sqrt(Math.Pow(p.X - cadx, 2) + Math.Pow(p.Y - cady, 2)) }); //组成新集合                                    
                                        if (hpoints.Any())
                                        {
                                            var _arr = hpoints.ToList().OrderBy(p => p.Distance).ToArray();
                                            var vpoint = mdb.VisionPoints.FirstOrDefault(point => point.Hand == 0 && point.PcsOrder == _arr[0].PcsOrder);
                                            if (vpoint != null)
                                            {
                                                int pcsorder = _pcsOrder++;
                                                vpoint.Track = i;
                                                vpoint.ImagePcsOrder = pcsorder;
                                                vpoint.ImageKind = 1;
                                                mdb.FlyGrabPoints.Add(new FlyGrabPoint
                                                {
                                                    PcsOrder = pcsorder,
                                                    Track = i,
                                                    Hand = 0,
                                                    Kind = 1,
                                                    X = Math.Round(cadx + leftdeltaX, 3),
                                                    Y = Math.Round(cady + leftdeltaY, 3),
                                                    Z = LeftCameraGrabZPos,
                                                    UseLight1 = true,
                                                    UseLight2 = true
                                                });
                                            }
                                        }

                                    }
                                }
                            }
                            mdb.SaveChanges();
                        }

                        var rightpolylines = dxf.LwPolylines.Where(l => l.Layer.Name == "RFP");
                        if (rightpolylines.Any())
                        {
                            var polylinelist = rightpolylines.ToList();
                            // 升序
                            polylinelist.Sort((x, y) => x.Vertexes.Min(v => v.Position.Y).CompareTo(y.Vertexes.Min(v => v.Position.Y)));
                            for (int i = 0; i < polylinelist.Count; i++)
                            {
                                //插入路径
                                mdb.FlyGrabPoints.Add(new FlyGrabPoint
                                {
                                    PcsOrder = 0,
                                    Hand = 1,
                                    Track = i,
                                    Kind = 2,
                                    X = Math.Round(polylinelist[i].Vertexes[0].Position.X - rminx + RightFirst.X + rightdeltaX, 3),
                                    Y = Math.Round(polylinelist[i].Vertexes[0].Position.Y - rminy + RightFirst.Y + rightdeltaY, 3),
                                    Z = RightCameraGrabZPos,
                                    UseLight1 = true,
                                    UseLight2 = true
                                });
                                int _endIndx = polylinelist[i].Vertexes.Count - 1;
                                mdb.FlyGrabPoints.Add(new FlyGrabPoint
                                {
                                    PcsOrder = 1,
                                    Hand = 1,
                                    Track = i,
                                    Kind = 2,
                                    X = Math.Round(polylinelist[i].Vertexes[_endIndx].Position.X - rminx + RightFirst.X + rightdeltaX, 3),
                                    Y = Math.Round(polylinelist[i].Vertexes[_endIndx].Position.Y - rminy + RightFirst.Y + rightdeltaY, 3),
                                    Z = RightCameraGrabZPos,
                                    UseLight1 = true,
                                    UseLight2 = true
                                });

                                var _minY = polylinelist[i].Vertexes[0].Position.Y - 0.5;
                                var _maxY = polylinelist[i].Vertexes[0].Position.Y + 0.5;
                                int _pcsOrder = 0;
                                var circles = dxf.Circles.Where(circle => circle.Layer.Name == "RFP" && circle.Center.Y >= _minY && circle.Center.Y < _maxY);
                                if (circles != null)
                                {
                                    var circleList = circles.ToList();
                                    //升序
                                    circleList.Sort((x, y) => Math.Abs(x.Center.X - polylinelist[i].Vertexes[0].Position.X).CompareTo(Math.Abs(y.Center.X - polylinelist[i].Vertexes[0].Position.X)));

                                    foreach (var item in circleList)
                                    {
                                        var cadx = item.Center.X - rminx + RightFirst.X;
                                        var cady = item.Center.Y - rminy + RightFirst.Y;
                                        var hpoints = mdb.XYZRPoints.Where(p => p.Hand == 1).Select(p => new { PcsOrder = p.PcsOrder, Distance = Math.Sqrt(Math.Pow(p.X - cadx, 2) + Math.Pow(p.Y - cady, 2)) }); //组成新集合                                    
                                        if (hpoints.Any())
                                        {
                                            var _arr = hpoints.ToList().OrderBy(p => p.Distance).ToArray();
                                            var vpoint = mdb.VisionPoints.FirstOrDefault(point => point.Hand == 1 && point.PcsOrder == _arr[0].PcsOrder);
                                            if (vpoint != null)
                                            {
                                                int pcsorder = _pcsOrder++;
                                                vpoint.Track = i;
                                                vpoint.ImagePcsOrder = pcsorder;
                                                vpoint.ImageKind = 1;
                                                mdb.FlyGrabPoints.Add(new FlyGrabPoint
                                                {
                                                    PcsOrder = pcsorder,
                                                    Track = i,
                                                    Hand = 1,
                                                    Kind = 1,
                                                    X = Math.Round(cadx + rightdeltaX, 3),
                                                    Y = Math.Round(cady + rightdeltaY, 3),
                                                    Z = RightCameraGrabZPos,
                                                    UseLight1 = true,
                                                    UseLight2 = true
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                            mdb.SaveChanges();
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }));
                    }

                });
                LoadLwPolyList();
                aggregator.SendMessage("UpdateDispMap", "Run");
                MessageBox.Show("导入图纸完成", "信息");
            }
            IsBusy = false;
        }
        #endregion
        #region 导航
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            LoadParam();
            LeftMark = new XYPointDisp {
                X = systemParam.LeftMark.X,
                Y = systemParam.LeftMark.Y
            };
            LeftDelta = new XYPointDisp { 
                X = systemParam.LeftDelta.X,
                Y = systemParam.LeftDelta.Y
            };
            RightMark = new XYPointDisp { 
                X= systemParam.RightMark.X,
                Y= systemParam.RightMark.Y
            };
            rightDelta = new XYPointDisp { 
                X= systemParam.RightDelta.X,
                Y= systemParam.RightDelta.Y
            };
            LoadLwPolyList();
            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
            PointList1.Clear();
            var leftpoints = mdb.XYZRPoints.Where(p => p.Hand == 0).OrderBy(p => p.PcsOrder);
            if (leftpoints.Any())
            {
                leftpoints.ToList().ForEach(p => {
                    PointList1.Add(new XYZPointDisp
                    {
                        Id = p.Id,
                        Alias = p.Alias,
                        Name = p.Name,
                        X = p.X,
                        Y = p.Y,
                        Z = p.Z,
                        H = p.H,
                        X1 = p.X1,
                        Y1 = p.Y1,
                        LazerDocumentIndex = p.LazerDocumentIndex + 1,
                        ProductIndex = p.ProductIndex + 1,
                        PcsOrder = p.PcsOrder,
                        IsUse = p.IsUse
                    });
                });
            }
            var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "XYJogSpeed");
            if (_mParam != null)
            {
                mxYJogSpeed = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZJogSpeed");
            if (_mParam != null)
            {
                mzJogSpeed = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZSafePos" && m.Hand == 0);
            if (_mParam != null)
            {
                mz1SafePos = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZSafePos" && m.Hand == 1);
            if (_mParam != null)
            {
                mz2SafePos = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "WeldZ" && m.Hand == 0);
            if (_mParam != null)
            {
                LeftWeldZ = _mParam.Value;
                mleftWeldZ = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "WeldH" && m.Hand == 0);
            if (_mParam != null)
            {
                LeftWeldH = _mParam.Value;
                mleftWeldH = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "WeldZ" && m.Hand == 1);
            if (_mParam != null)
            {
                RightWeldZ = _mParam.Value;
                mrightWeldZ = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "WeldH" && m.Hand == 1);
            if (_mParam != null)
            {
                RightWeldH = _mParam.Value;
                mrightWeldH = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "BornH" && m.Hand == 0);
            if (_mParam != null)
            {
                LeftBornH = _mParam.Value;
                mleftBornH = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "BornH" && m.Hand == 1);
            if (_mParam != null)
            {
                RightBornH = _mParam.Value;
                mrightBornH = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "First" && m.Hand == 0);
            if (_mParam != null)
            {
                try
                {
                    var _point = JsonConvert.DeserializeObject<MPoint>(_mParam.Value);
                    LeftFirst = new XYPointDisp { X = _point.X, Y = _point.Y };
                }
                catch
                {
                    LeftFirst = new XYPointDisp { X = 0, Y = 0 };
                    MPoint _point1 = new MPoint { X = 0, Y = 0, Z = 0 };
                    _mParam.Value = JsonConvert.SerializeObject(_point1, Formatting.Indented);
                    _mParam.Type = typeof(MPoint).Name;
                    mdb.SaveChanges();
                }
            }
            else
            {
                LeftFirst = new XYPointDisp { X = 0, Y = 0 };
                MPoint _point = new MPoint { X = 0, Y = 0, Z = 0 };
                mdb.MParams.Add(new MParam
                {
                    Name = "First",
                    Hand = 0,
                    Type = typeof(MPoint).Name,
                    Value = JsonConvert.SerializeObject(_point, Formatting.Indented)
                });
                mdb.SaveChanges();
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "First" && m.Hand == 1);
            if (_mParam != null)
            {
                try
                {
                    var _point = JsonConvert.DeserializeObject<MPoint>(_mParam.Value);
                    RightFirst = new XYPointDisp { X = _point.X, Y = _point.Y };
                }
                catch {
                    RightFirst = new XYPointDisp { X = 0, Y = 0 };
                    MPoint _point1 = new MPoint { X = 0, Y = 0, Z = 0 };
                    _mParam.Value = JsonConvert.SerializeObject(_point1, Formatting.Indented);
                    _mParam.Type = typeof(MPoint).Name;
                    mdb.SaveChanges();
                }
            }
            else
            {
                RightFirst = new XYPointDisp { X = 0, Y = 0 };
                MPoint _point = new MPoint { X = 0, Y = 0, Z = 0 };
                mdb.MParams.Add(new MParam
                {
                    Name = "First",
                    Hand = 1,
                    Type = typeof(MPoint).Name,
                    Value = JsonConvert.SerializeObject(_point, Formatting.Indented)
                });
                mdb.SaveChanges();
            }
            _mParam = mdb.MParams.FirstOrDefault(p => p.Name == "CameraGrabZPos" && p.Hand == 0);
            if (_mParam != null)
            {
                if (double.TryParse(_mParam.Value,out var v1))
                {
                    LeftCameraGrabZPos = v1;
                }
                else
                {
                    LeftCameraGrabZPos = -50;
                    _mParam.Value = LeftCameraGrabZPos.ToString();
                    _mParam.Type = typeof(double).Name;
                    mdb.SaveChanges();
                }
            }
            else
            {
                LeftCameraGrabZPos = -50;
                mdb.MParams.Add(new MParam
                {
                    Name = "CameraGrabZPos",
                    Type = typeof(double).Name,
                    Value = LeftCameraGrabZPos.ToString(),
                    Hand = 0
                });
                mdb.SaveChanges();
            }
            _mParam = mdb.MParams.FirstOrDefault(p => p.Name == "CameraGrabZPos" && p.Hand == 1);
            if (_mParam != null)
            {
                if (double.TryParse(_mParam.Value, out var v1))
                {
                    RightCameraGrabZPos = v1;
                }
                else
                {
                    RightCameraGrabZPos = -50;
                    _mParam.Value = LeftCameraGrabZPos.ToString();
                    _mParam.Type = typeof(double).Name;
                    mdb.SaveChanges();
                }
            }
            else
            {
                RightCameraGrabZPos = -50;
                mdb.MParams.Add(new MParam
                {
                    Name = "CameraGrabZPos",
                    Type = typeof(double).Name,
                    Value = RightCameraGrabZPos.ToString(),
                    Hand = 1
                });
                mdb.SaveChanges();
            }
        }
        public override void OnDialogClosed()
        {
            if (source1 != null)
            {
                source1.Cancel();
            }
        }
        #endregion
        #region 构造函数
        public WorkPointDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            Title = "工作点";
            IsBusy = false;
            HandIndex = 0;
            PointListSelectedIndex = -1;
            LwPolylineList = new ObservableCollection<LwPolylineDisp>();
            PointList1 = new ObservableCollection<XYZPointDisp>();
            gTSCard = containerProvider.Resolve<IGTSCardService>("GTSCard");
        }
        #endregion
        #region 功能函数
        void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"));
                systemParam = JsonConvert.DeserializeObject<Param>(jsonString);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
        void LoadLwPolyList()
        {
            try
            {
                DrawWidth = (systemParam.BorderWidth + 40) / 2;
                DrawHeight = (systemParam.BorderHeight + 40) / 2;
                LwPolylineList.Clear();
                LwPolylineList.Add(new LwPolylineDisp {
                    Id = 0,
                    Kind = 0,
                    Hand = 0,
                    Left = 10,
                    Bottom = 10,
                    Width = systemParam.BorderWidth / 2,
                    Height = systemParam.BorderHeight / 2,
                    BorderColor = "#0000FF",
                    BorderThickness = 1
                });
                using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                var _leftpoints = mdb.XYZRPoints.Where(p => p.Hand == 0).OrderByDescending(p => p.PcsOrder);
                if (_leftpoints.Any())
                {
                    _leftpoints.ToList().ForEach(p => {
                        LwPolylineList.Add(new LwPolylineDisp
                        {
                            Id = p.Id,
                            Kind = 2,
                            Hand = 0,
                            Left = 10 + (p.X - 10) / 2,
                            Bottom = 10 + (p.Y - 10) / 2,
                            Width = 10,
                            Height = 10,
                            BorderColor = "#7B68EE",
                            BorderThickness = 1
                        });
                    });
                }
                var _rightpoints = mdb.XYZRPoints.Where(p => p.Hand == 1).OrderByDescending(p => p.PcsOrder);
                if (_rightpoints.Any())
                {
                    _rightpoints.ToList().ForEach(p => {
                        LwPolylineList.Add(new LwPolylineDisp
                        {
                            Id = p.Id,
                            Kind = 2,
                            Hand = 1,
                            Left = 10 + (p.X - 10) / 2,
                            Bottom = 10 + (p.Y - 10) / 2,
                            Width = 10,
                            Height = 10,
                            BorderColor = "#FF007F",
                            BorderThickness = 1
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
        private void JumpAction(CancellationToken token, double tartgetX, double tartgetY, double tartgetZ, AxisParm axisX, AxisParm axisY, AxisParm axisZ, double ZSafe)
        {
            try
            {
                int stepnum = 0;
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    switch (stepnum)
                    {
                        case 0://Z运动到安全位
                            {
                                GTSCard.AxisPosMove(ref axisZ, ZSafe, mzJogSpeed);
                                stepnum = 1;
                            }
                            break;
                        case 1:
                            if (GTSCard.AxisPosMoveCheckDone(axisZ))
                            {
                                stepnum = 2;
                            }
                            break;
                        case 2:
                            {
                                GTSCard.AxisPosMove(ref axisX, tartgetX, mxYJogSpeed);
                                GTSCard.AxisPosMove(ref axisY, tartgetY, mxYJogSpeed);
                                stepnum = 3;
                            }
                            break;
                        case 3:
                            if (GTSCard.AxisPosMoveCheckDone(axisX) && GTSCard.AxisPosMoveCheckDone(axisY))
                            {
                                stepnum = 4;
                            }
                            break;
                        case 4:
                            {
                                GTSCard.AxisPosMove(ref axisZ, tartgetZ, mzJogSpeed);
                                stepnum = 5;
                            }
                            break;
                        case 5:
                            if (GTSCard.AxisPosMoveCheckDone(axisZ))
                            {
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Debug.WriteLine(ex.Message);
            }
        }
        private void GoAction(CancellationToken token, double tartgetX, double tartgetY, double tartgetZ, AxisParm axisX, AxisParm axisY, AxisParm axisZ)
        {
            try
            {
                int stepnum = 0;
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    switch (stepnum)
                    {
                        case 0:
                            {
                                GTSCard.AxisPosMove(ref axisX, tartgetX, mxYJogSpeed);
                                GTSCard.AxisPosMove(ref axisY, tartgetY, mxYJogSpeed);
                                GTSCard.AxisPosMove(ref axisZ, tartgetZ, mzJogSpeed);
                                stepnum = 1;
                            }
                            break;
                        case 1:
                            if (GTSCard.AxisPosMoveCheckDone(axisX) && GTSCard.AxisPosMoveCheckDone(axisY) &&
                                GTSCard.AxisPosMoveCheckDone(axisZ))
                            {
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Debug.WriteLine(ex.Message);
            }

        }
        #endregion
    }
}
